<?php

namespace App\Http\Controllers\Api;

use App\Models\Book;
use App\Models\User;
use App\Models\UserCart;
use App\Models\UserLikeCategory;
use Illuminate\Http\Request;
use App\Common\ErrorCode;

class UserCartsController extends BaseController
{
    public function store(Request $request)
    {
        $user_id = intval($request->input('user_id'));
        $book_id = intval($request->input('book_id'));

        if(empty($user_id) || empty($book_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $book = Book::query()->where('deleted',0)->find($book_id);
        if(empty($book))
        {
            return $this->error(10000,'图书不存在');
        }

        $user = User::query()->find($user_id);

        if($user->carts()->where('book_id',$book_id)->first())
        {
            return $this->error(10000,'已在书架');
        }

        $cart = new UserCart();
        $cart->user()->associate($user);
        $cart->book()->associate($book_id);
        $cart->save();

        UserLikeCategory::addUserLikeCategoryScore($this->user_id,$book->category_id,UserLikeCategory::CART_WEIGHT);

        return $this->success();
    }

    public function index(Request $request)
    {
        $carts = UserCart::query()->with(['book'])->where('user_id',$this->user_id)->orderBy('id','desc')->get();

        $data = [];
        if(!empty($carts))
        {
            foreach ($carts as $cart)
            {
                $data[] = [
                    'id' => $cart->id,
                    'book_id' => $cart->book_id,
                    'title' => $cart->book->title,
                    'store' => $cart->book->store,
                    'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$cart->book->image,
                ];
            }
        }
        return $this->res([
            'data' => $data
        ]);
    }

    public function delete(Request $request)
    {
        $cart_ids = $request->input('cart_ids');

        $cart_ids_arr = explode(',',$cart_ids);

        if(empty($cart_ids) || empty($cart_ids_arr) || !is_array($cart_ids_arr))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        foreach ($cart_ids_arr as $v)
        {
            $cart = UserCart::query()->find($v);
            if(empty($cart))
            {
                continue;
            }
            $book = Book::query()->find($cart->book_id);
            UserLikeCategory::decreaseUserLikeCategoryScore($this->user_id,$book->category_id,UserLikeCategory::CART_WEIGHT);
            UserCart::destroy($v);
        }

        return $this->success();
    }
}
